package com.yssoft.service.core;

import cn.hutool.json.JSONObject;
import com.yssoft.entity.FileUpload;
import com.yssoft.utils.MultipartFileResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Service
public class FileUploadService {

    @Resource
    private RestTemplate restTemplate;
    @Value("${fast_url}")
    private String fastUrl;
    // 目标上传接口URL
    private static final String UPLOAD_URL = "/app/file/upload";

    /**
     * 上传文件到目标服务
     *
     * @param file 要上传的文件
     * @return 上传结果
     */
    public FileUpload uploadFile(MultipartFile file) {
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 创建文件资源
            MultipartFileResource resource = new MultipartFileResource(file);

            // 构建请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", resource);
            // 可以添加其他参数
            // body.add("fileName", file.getOriginalFilename());
            // body.add("uploadUser", "spring-mvc-client");

            // 创建请求实体
            HttpEntity<MultiValueMap<String, Object>> requestEntity =
                    new HttpEntity<>(body, headers);
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                    fastUrl + UPLOAD_URL,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            if (response.getStatusCode() == HttpStatus.OK) {
                String result = response.getBody();
                FileUpload fileUpload = new FileUpload();
                // 修复乱码：将ISO-8859-1解码的字符串重新转换为UTF-8
                String fixedResult = new String(result.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                JSONObject jsonObject = new JSONObject(fixedResult);
                fileUpload.setId(jsonObject.get("id").toString());
                fileUpload.setFilePath(jsonObject.get("path").toString());
                return fileUpload;
            } else {
                throw new RuntimeException("上传失败，状态码: " + response.getStatusCode());
            }

        } catch (Exception e) {
            throw new RuntimeException("文件上传异常: " + e.getMessage());
        }
    }

}